﻿using System.IO;
using System.IO.Compression;

namespace CommonFramework.Serialize.BytesArray
{
    public static class BytesCompressUtil
    {
        public static byte[] CompressBytes(byte[] data)
        {
            if (data == null || data.Length == 0)
                return data;

            using (var output=new MemoryStream())
            {
                using (var deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
                {
                    using (var input = new MemoryStream(data))
                    {
                        input.CopyTo(deflateStream);
                    }
                }
                return output.ToArray();
            }
        }

        public static byte[] UncompressBytes(byte[] data)
        {
            if (data == null || data.Length == 0)
                return data;

            using (var input = new MemoryStream(data))
            {
                using (var deflateStream = new DeflateStream(input, CompressionMode.Decompress))
                {
                    using (var output = new MemoryStream())
                    {
                        deflateStream.CopyTo(output);
                        return output.ToArray();
                    }
                }
            }
        }
    }
}